package com.kot32.dynamicloadviewlibrary.core;

import ark.system.ClassLoaderCreator;
import com.kot32.dynamicloadviewlibrary.delegate.IDynamic;
import com.kot32.dynamicloadviewlibrary.model.DynamicViewInfo;
import com.kot32.dynamicloadviewlibrary.util.DisplayUtil;
import com.kot32.dynamicloadviewlibrary.util.LogUtil;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.utils.TextTool;
import ohos.app.Context;

import java.io.File;
import java.lang.reflect.Constructor;
import java.util.Objects;


public class DynamicViewGroup extends DependentLayout implements IDynamic, Component.EstimateSizeListener {

    public static final String ATTRIBUTE_UUID = "dvg_uuid";

    // the uuid of view, when update it can matches the view has same uuid .
    private String uuid = "";

    private Component dynamicView;

    public DynamicViewGroup(Context context) {
        super(context);
        init();
    }

    public DynamicViewGroup(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initXmlAttrs(attrSet);
        init();
    }

    void initXmlAttrs(AttrSet attrSet) {
        boolean present = attrSet.getAttr(ATTRIBUTE_UUID).isPresent();
        uuid = present ? attrSet.getAttr(ATTRIBUTE_UUID).get().getStringValue() : "";
    }

    private void init() {
        DynamicViewManager.getInstance().addViewGroup(this);
        setEstimateSizeListener(this);
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {

        update();
        return false;
    }

    /**
     * Auto update when App restart
     */
    @Override
    public void update() {
        LogUtil.i("execute update");
        if (TextTool.isNullOrEmpty(DynamicViewManager.getInstance().getUpdateFileFullPath())) return;
        File apkFile = new File(DynamicViewManager.getInstance().getUpdateFileFullPath());
        LogUtil.i("dynamic file path: %s, exist: %b", DynamicViewManager.getInstance().getUpdateFileFullPath(), apkFile.exists());
        if (apkFile.exists()) {
            ClassLoader classLoader = ClassLoaderCreator.createClassLoader(apkFile.getAbsolutePath(), getContext().getClassloader());
            if (DynamicViewManager.getInstance().getDynamicInfo() == null) return;
            for (DynamicViewInfo viewInfo : DynamicViewManager.getInstance().getDynamicInfo().viewInfo) {
                if (viewInfo != null) {
                    if (viewInfo.uuid.equals(uuid)) {
                        try {
                            Class newViewClazz = classLoader.loadClass(viewInfo.packageName);
                            Constructor con = newViewClazz.getConstructor(Context.class);
                            //first use Activity's Resource lie to View
                            if (dynamicView == null) {
                                dynamicView = (Component) con.newInstance(getContext());
                            }
                            LayoutConfig layoutConfig = new LayoutConfig(
                                    DisplayUtil.vp2px(getContext(), viewInfo.layoutParams.width),
                                    DisplayUtil.vp2px(getContext(), viewInfo.layoutParams.height));
                            LogUtil.i("width: %d, height: %d", layoutConfig.width, layoutConfig.height);
                            layoutConfig.addRule(LayoutConfig.CENTER_IN_PARENT);
                            if (getChildCount()>0)removeAllComponents();
                            addComponent(dynamicView, layoutConfig);
                            LogUtil.i("add component success");
                        } catch (Exception e) {
                            LogUtil.i("error msg: %s", e.getLocalizedMessage());
                            e.printStackTrace();
                        }
                    }
                }
            }
            invalidate();
        }

    }


    protected void onFinishInflate() {
        if (DynamicViewManager.getInstance().getShouldUpdate()) {
            update();
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DynamicViewGroup that = (DynamicViewGroup) o;

        return Objects.equals(uuid, that.uuid);

    }

    @Override
    public int hashCode() {
        return uuid != null ? uuid.hashCode() : 0;
    }

    public Component getDynamicView() {
        if (dynamicView == null) {
            if (getComponentAt(0) != null) {
                return getComponentAt(0);
            }
        }
        return dynamicView;
    }

}
